import { Component } from 'react';

import {Boxs,Button,Popup,Dialog} from 'saltui';
const { HBox, Box} = Boxs;
import TableSelect from './table';
import TreeSelect from './tree';
import TreeTableSelect from './treetable';
import utils from './utils';

import 'whatwg-fetch';
import 'es6-promise';

export default class PageHome extends Component {

  constructor(props) {
    super(props);
    let t = this;

    var baseContext = document.getElementById("baseContext").value;

    var token = document.getElementById("token").value;
    this.state = {
        search:'',
        change:true,
        selectText:'',

        data: [],
        selectedData:[],
        selectNum:0,
        checked:'checkbox',
        placeholder:'搜索',
        showName:'text',

        visible:false,
        top:0,

        baseContext:baseContext,
        token:token,
        corpId:'0',

        popType:'table',

        searchField:'text',
    }

    t.listener = t.handleHidePopup.bind(t);
  }

  componentDidMount(){
  } 

  // 去除监听并关闭弹出页
  handleHidePopup() {
    const t = this;
    window.removeEventListener('popstate', t.listener, false);
    t.setState({
      visible: false,
    }, () => {
        let popType = t.state.popType;
        if (popType == 'tree') {
            t.refs.tree.initState();
        } else if (popType == 'treetable') {
            t.refs.treetable.initState();
        } else {
            t.refs.table.initState();
        }
        $("#App").removeAttr("style");
        $(document).scrollTop(t.state.top);
    });
  }

  // 选择确认
  selectConfirm(result){
      let t = this;
      // 是否是对接系统弹出选择
      let popCode = t.props.popCode;
      if (popCode == null || popCode == 'null' || popCode == '' || popCode == undefined || popCode == 'undefined') {
        popCode = '';
      }

      if (popCode == '') {
          // 不关联PC弹出选择
          this.props.onChange(result);
      } else {
          // 关联PC弹出选择

          // 回显的属性
          let showName = this.state.showName;
          // 单选多选标识
          let checked = this.state.checked;

          // 回显的值
          let returnValue = '';
          if (checked == 'radio') {
             // 单选
             returnValue = result[showName];
             if (returnValue == null || returnValue == 'null' || returnValue == '' || returnValue == undefined || returnValue == 'undefined') {
                  returnValue = '';
             }
          } else {
             // 多选
             if (result != null && result.length > 0) {
               for (var h = 0; h < result.length; h++) {
                  var rObj = result[h];
                  var show = rObj[showName];
                  if (show != null && show != 'null' && show != '' && show != undefined && show != 'undefined') {
                      if (returnValue == '') {
                          returnValue = show;
                      } else {
                          returnValue += ',' + show;
                      }
                  }
               }
             }
          }
          this.props.onChange(returnValue);
      }
      history.back();
  }

   // 触发弹出选择
   popupFuc(){
      let t = this;
      // 只读状态
      let readOnly = this.props.readOnly;
      if (readOnly) {
         return false;
      }

      // 当前页面的高度
      var top = $(window).scrollTop();
      // 控制底层页面不可动
      $('#App').css("top",-top+"px");
      $('#App').css("width",100+"%");
      $('#App').css('position','fixed');

      // 是否是对接系统弹出选择
      let popCode = t.props.popCode;
      let popType = "";
      if (popCode == null || popCode == 'null' || popCode == '' || popCode == undefined || popCode == 'undefined') {
        popCode = '';
        popType = 'table';
      }


      // 单选多选标识
      let checked = this.props.checked;
      if (checked == null || checked == 'null' || checked == '' || checked == undefined || checked == 'undefined') {
        checked = 'checkbox';
      }

      // 搜索提示语
      let placeholder = this.props.placeholder;
      if (placeholder == null || placeholder == 'null' || placeholder == '' || placeholder == undefined || placeholder == 'undefined') {
          placeholder = '搜索';
      }

      // 回显属性名
      let showName = this.props.showName;
      if (showName == null || showName == 'null' || showName == '' || showName == undefined || showName == 'undefined') {
          showName = 'text';
      }

      // 搜索属性
      let searchField = this.props.searchField;
      if (searchField == null || searchField == 'null' || searchField == '' || searchField == undefined || searchField == 'undefined') {
          searchField = 'text';
      }

      // 选择列表数据
      let data = this.props.data;
      // 被选中的个数
      let selectNum = 0;
      // 选中的数据
      let value = this.props.value;
    
      // 请求后台获取弹出数据
      if (popCode != '') {
          // 调用弹出选择Api接口
          var url = this.state.baseContext + "/api/m/cmp/poppage/getPoppageInfo?token="+this.state.token+"&corpId="+this.state.corpId+"&popCode="+popCode;
          fetch(url,{
            method: "GET",
            mode: "cors",
            headers: {
              'Accept': 'application/json, text/plain, */*',
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          }).then((response) => response.json()).then((result) => {
            // 选中数据处理
            let tempData1 = null;
            // 获取数据成功
            if (result != null && result.type == 'success') {
              // 弹出选择数据
              let popData = result.data;
              // 弹出类型
              popType = popData.popType;
              // 显示字段
              if (popType == 'treetable') {
                  Dialog.alert({
                    content: '暂不支持树-列表格式的弹出选择！',
                    onConfirm() {
                      $("#App").removeAttr("style");
                      $(document).scrollTop(top);
                    },
                  });
                  return false;
              } else if (popType == 'tree') {
                  showName = 'name';
              } else {
                  showName = popData.queryShowfield;
              }

              // 查询字段
              let queryCondition = popData.queryCondition;
              if (queryCondition != '' && queryCondition != null) {
                  let tempCondition = '';
                  let conditionArr = queryCondition.split(';');
                  if (conditionArr != null && conditionArr.length > 0) {
                      for (var i = conditionArr.length - 1; i >= 0; i--) {
                        var obj = conditionArr[i];
                        if (obj != '' && obj != null) {
                           var objArr = obj.split(',');
                           if (objArr != null && objArr.length > 0) {
                              if (tempCondition == '') {
                                  tempCondition = objArr[0];
                              } else {
                                  tempCondition += ',' + objArr[0];
                              }
                           }
                        }
                      }
                  }
                  queryCondition = tempCondition;
              }

              searchField = queryCondition;
              
              // 选择列表数据
              data = popData.data;
              if (value != null && value != 'null' && value != '' && value != undefined && value != 'undefined') {
                        
                if (checked == 'radio') {
                  tempData1 = {};
                    // 单选
                    for (var k = 0; k < data.length; k++) {
                        var obj = data[k];
                        if (obj[showName] == value) {
                            tempData1 = obj;
                            break;
                        }
                    }
                } else {
                  // 多选
                  tempData1 = [];

                  // 选中得值
                  var valueArr = value.split(',');

                  // 验证标识
                  let checkStr = '';
                  for (var kk = 0; kk < data.length; kk++) {
                    var dobj = data[kk];

                    var id = dobj.value;
                    for (var jj = 0; jj < valueArr.length; jj++) {
                        var valueStr = valueArr[jj];
                        if (dobj[showName] == valueStr) {
                            tempData1.push(dobj);
                            valueArr.splice(jj,1);
                            break;
                        }
                    }
                  }
                }
              }
            }
            
            this.setState({
                change:true,
                data:data,
                selectNum:selectNum,
                checked:checked,
                placeholder:placeholder,
                selectedData:tempData1,
                showName:showName,
                popType:popType,
                top:top,
                visible: true,
                searchField:searchField,
                historyStamp: `SearchPanel.index_${Date.now()}`,
              }, () => {
                if (popType == 'tree') {
                    t.refs.tree.initState();
                } else if (popType == 'treetable') {
                    t.refs.treetable.initState();
                } else {
                    t.refs.table.initState();
                }

                window.history.pushState({
                  Poppage: t.state.historyStamp,
                }, '', utils.addUrlParam('POPPAGE', Date.now()));
                window.addEventListener('popstate', t.listener, false);
            });

          }).catch((error) => {
            alert("错误："+error);
          });
      } else {
          this.setState({
              change:true,
              data:data,
              selectNum:selectNum,
              checked:checked,
              placeholder:placeholder,
              selectedData:value,
              showName:showName,
              popType:popType,
              top:top,
              visible: true,
              searchField:searchField,
              historyStamp: `SearchPanel.index_${Date.now()}`,
            }, () => {
              t.refs.table.initState();
                
              window.history.pushState({
                Poppage: t.state.historyStamp,
              }, '', utils.addUrlParam('POPPAGE', Date.now()));
              window.addEventListener('popstate', t.listener, false);
          });
      }

   }

   // 点击蒙层关闭
   closMask(){
      history.back();
   }

  render() {
    const t = this;
    let selectText = '';
    // 必选标识
    let required = this.props.required;

    // label
    let label = this.props.label;
    if (label == null || label == 'null' || label == '' || label == undefined || label == 'undefined') {
        label = '弹出选择';
    }

    // 是否回显
    let isShow = this.props.isShow;

    // 是否显示箭头
    let isIcon = this.props.isIcon;

    // 表现形式：  0：常规，1：按钮  默认：常规
    let showType = this.props.showType;
    if (showType == null || showType == 'null' || showType == '' || showType == undefined || showType == 'undefined') {
        showType = '0';
    }

    // 单选多选标识
    let checked = this.props.checked;
    if (checked == null || checked == 'null' || checked == '' || checked == undefined || checked == 'undefined') {
      checked = 'checkbox';
    }

    let popCode = t.props.popCode;
    if (popCode == null || popCode == 'null' || popCode == '' || popCode == undefined || popCode == 'undefined') {
      popCode = '';
    }

    if (popCode != '') {
        // 关联PC端弹出选择 
        let value = this.props.value;
        if (value == null  || value == 'null' || value == '' || value == undefined || value == 'undefined') {
            value = '';
        }
        selectText = value;
    } else {
        // 不是PC端的弹出选择 
        // 选中的数据
        let value = this.props.value;
        let showName = this.props.showName;
        if (showName == null || showName == 'null' || showName == '' || showName == undefined || showName == 'undefined') {
          showName = this.state.showName;
        }
        // 单选
        if (checked == 'radio') {
            if (value != null && value != 'null' && value != '' && value != undefined && value != 'undefined') {
              selectText = '';
              selectText = value[showName];
            }
        } else {
          // 多选
          if (value == null || value == 'null' || value == '' || value == undefined || value == 'undefined') {
            value = [];
          }
          selectText = '';
          for (var ii=0;ii<value.length;ii++) {
              var obj = value[ii];
              if (selectText == '') {
                  selectText = obj[showName];
              } else {
                  selectText = selectText + ',' + obj[showName];
              }
          }      
        }
    }

    // 只读状态
    let readOnly = this.props.readOnly;

    return (
      <div >
        <div>
          <div className={showType == '1' ? 'demo-section' : 't-DN'} >
            <div className="section-content">
                <Button type="primary" onClick={() => {this.popupFuc(); }}>{label}</Button>
            </div>
          </div>

          <HBox vAlign="center" className={showType!='1' ? 't-FS16 t-PL16 t-PR16' : 't-DN'} onClick={() => {this.popupFuc(); }}>
              <Box className={required ? 't-field-layout-h-label required' : 't-field-layout-h-label'}>{label}</Box>
              <HBox flex={1} >
                <Box flex={1} className={isShow ? 't-DN' : 't-FAL t-LH1_4 t-omit'}>{selectText}</Box>
                <Box className={isIcon || readOnly ? 't-DN' : 't-PR4'}>
                  <b className="iconfont icon-back t-rotate-180 t-FCc t-FS16 t-FS14"></b>
                </Box>
              </HBox>
          </HBox>
        </div>

        <TableSelect className={this.state.popType == 'table' ? '' : 't-DN'}
           placeholder={this.state.placeholder}
           data={this.state.data}
           onChange={this.selectConfirm.bind(this)}
           closMask={this.closMask.bind(this)}
           value={this.state.selectedData}
           checked={this.state.checked}
           showName={this.state.showName}
           visible={this.state.visible}
           top={this.state.top}
           searchField={this.state.searchField}
           ref="table"
        />

        <TreeSelect className={this.state.popType == 'tree' ? '' : 't-DN'}
           placeholder={this.state.placeholder}
           data={this.state.data}
           onChange={this.selectConfirm.bind(this)}
           closMask={this.closMask.bind(this)}
           value={this.state.selectedData}
           checked={this.state.checked}
           showName={this.state.showName}
           visible={this.state.visible}
           top={this.state.top}
           searchField={this.state.searchField}
           ref="tree"
        />

        <TreeTableSelect className={this.state.popType == 'treetable' ? '' : 't-DN'}
           placeholder={this.state.placeholder}
           data={this.state.data}
           onChange={this.selectConfirm.bind(this)}
           closMask={this.closMask.bind(this)}
           value={this.state.selectedData}
           checked={this.state.checked}
           showName={this.state.showName}
           visible={this.state.visible}
           top={this.state.top}
           searchField={this.state.searchField}
           ref="treetable"
        />

     </div>   
    )
  }
}

